<?php


namespace Tbf\Component\Image;


use Symfony\Component\HttpFoundation\Response;
use Tbf\Component\FileSystem\FileSystemFunction;
use Tbf\Component\Path\PathFunction;

class ImageFunction {
    public static function newFontDraw(){
        return new FontDraw();
    }
    public static function newRectangle(){
        return new Rectangle();
    }
    public static function newRectangleOnPoint($left,$top,$right,$bottom){
        $obj = new Rectangle;
        $obj->setX($left);
        $obj->setY($top);
        $obj->setHeight($bottom-$top);
        $obj->setWidth($right-$left);
        return $obj;
    }
    public static function newRectangleOnSize($x,$y,$width,$height){
        $obj = new Rectangle;
        $obj->setX($x)
            ->setY($y)
            ->setHeight($height)
            ->setWidth($width);
        return $obj;
    }
    public static function newRectangleOnGdImage($image){
        return ImageFunction::newRectangleOnSize(
            0,
            0,
            imagesx($image),
            imagesy($image)
        );
    }
    public static function getEnFontPath(){
        return __DIR__.'/Resources/en.ttf';
    }
    public static function getVerifyFontPath(){
        return __DIR__.'/Resources/verify.ttf';
    }
    public static function wideImageToResponse(\WideImage_Image $image,$type='png'){
        $resp = new Response($image->asString($type));
        $resp->headers->set('Content-Type','image/'.$type);
        return $resp;
    }

    /**
     * 设置图片的dpi信息
     * @param $string
     */
    public static function setDpiInImageString($string,$dpi,$type='jpeg'){
        $type = strtolower($type);
        if ($type!=='jpeg'&&$type!=='jpg'){
            throw new \Exception('setDpiInImageString: not implement set dpi in '.$type);
        }
        //设置jpeg的尺寸
        return substr_replace($string, pack("cnn", 1, (int)$dpi, (int)$dpi), 13, 5);
    }

    /**
     * 设置图片的dpi信息
     * @param $string
     */
    public static function setDpiInImageFile($file_path,$dpi){
        $type = PathFunction::getExtension($file_path);
        //设置jpeg的尺寸
        $content = file_get_contents($file_path);
        $content = self::setDpiInImageString($content,$dpi,$type);
        file_put_contents($file_path,$content);
    }
}